﻿using System;
using System.Collections.Generic;

namespace PlottingBasics.LINQHelpers
{
    public static class TakeAllButCount
    {
        /// <summary>
        /// Returns an iterator that will give all elements in a sequence except for the last n. Null sequence
        /// if you ask for more than are there.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="leaveLast"></param>
        /// <returns></returns>
        public static IEnumerable<T> TakeAllBut<T>(this IEnumerable<T> source, int leaveLast)
        {
            return new TakeAllButItr<T>(source, leaveLast);
        }

        class TakeAllButItr<T> : IEnumerable<T>
        {
            private IEnumerable<T> _source;
            private int _leaveLastN;

            public TakeAllButItr(IEnumerable<T> source, int leaveLast)
            {
                // TODO: Complete member initialization
                this._source = source;
                this._leaveLastN = leaveLast;
            }

            public System.Collections.Generic.IEnumerator<T> GetEnumerator()
            {
                Queue<T> queue = new Queue<T>();
                foreach (var item in _source)
                {
                    queue.Enqueue(item);
                    if (queue.Count > _leaveLastN)
                    {
                        yield return queue.Dequeue();
                    }
                }
            }

            #region IEnumerable Members

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                throw new NotImplementedException();
            }

            #endregion
        }

    }
}
